package news;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TopicDao {

	// findALL,add,delete,update方法

	public List<Topic> findALL() {
		String sql = "SELECT * FROM topic;";
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Topic> list = new ArrayList();
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				Topic t = new Topic();
				t.setTid(rs.getInt("tid"));
				t.setTname(rs.getString("tname"));
				list.add(t);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, conn);
		}
		return list;
	}

	public int add(Topic t) {
		String sql = "INSERT INTO  topic(tname) VALUES(?);";
		return DBUtil.executeUpdate(sql, t.getTname());
	}

	public int del(int tid) {
		String sql = "DELETE FROM topic WHERE tid=?;";
		return DBUtil.executeUpdate(sql, tid);
	}

	public int del(String tname) {
		String sql = "DELETE FROM topic WHERE tname=?;";
		return DBUtil.executeUpdate(sql, tname);
	}

	public int update(Topic t) {
		String sql = "UPDATE topic SET tname=? WHERE tid=?;";
		return DBUtil.executeUpdate(sql, t.getTname(), t.getTid());
	}
}